package com.itheima.d6_tcp3;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    public static ArrayList<Socket> list = new ArrayList<>();
    public static void main(String[] args) throws IOException {

        final ExecutorService pool = Executors.newFixedThreadPool(80);
        final ServerSocket serverSocket = new ServerSocket(6666);

        while (true) {
            final Socket socket = serverSocket.accept();

            list.add(socket);

            pool.execute(new user(socket));
        }


    }
}

class user implements Runnable{

private final Socket  socket;

    public user(Socket socket) {
        this.socket = socket;

    }

    @Override
    public void run() {
        try {
            final DataInputStream dis = new DataInputStream(socket.getInputStream());
            while (true) {

                String s = dis.readUTF();
                System.out.println(s);

                for (Socket socket1 : Server.list) {
                    if(!socket1.equals(socket)){
                            sendMsg(s,socket1);
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    public  void  sendMsg(String s,Socket socket) throws IOException {
        final DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeUTF(s);
    }
}
